let testInterface  = "http://testapi2.xunyinjiaoyou.com"// 测试     
// let testInterface = 'https://api2.xunyinjiaoyou.com' //正式                             

const CryptoJS = require('../utils/crypto.js');  
let md5 = require("../utils/md5.js") 
 
function axios(option) {  
  let time = Date.parse(new Date());
  if (wx.getStorageSync("newtime")) {
    time = Number(time) + Number(wx.getStorageSync("newtime"));
  } else {    
    time = time;
  }
  if (wx.getStorageSync("shumeiDeviceId")) {
    option.data.shumeiDeviceId = wx.getStorageSync("shumeiDeviceId");
  } else { 
    delete option.data.shumeiDeviceId
  } 
  if (wx.getStorageSync("UserInformation")) {
    option.data.userId = wx.getStorageSync("UserInformation").userId;
    option.data.token = wx.getStorageSync("UserInformation").token;
  }
  if (!option.data.clientId) {
    delete option.data.clientId
  }
  delete option.data.sign
  option.data.time = time;
  option.data.device_id = wx.getStorageSync("unionid");
  option.data.channel_code = "gongzhonghao";
  option.data.source = "xiaochengxu"; 
  option.data.version = "1.0.5";
  let _token = this.encryption(option.data); 
  option.data.sign = md5.hexMD5(_token);
  // console.log(_token);
  return new Promise((resolve, reject) => {
    wx.request({
      url: testInterface + option.url,
      data: option.data,
      method: 'POST',
      success: (data) => {
        resolve(data)
      },
      catch: (err) => {
        reject(err)
      }
    })
  })
}
const key = CryptoJS.enc.Utf8.parse("q2r402f0203eu89l"); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('z09t3f62q28w068q'); //十六位十六进制数作为密钥偏移量
//解密方法
function Decrypt(word) {
  let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

//加密方法
function Encrypt(word) {
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString().toUpperCase();
}


//对象转数组并倒序
function reverse(arys) {
  var newkey = Object.keys(arys).sort().reverse();
  var newObj = {};
  for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = arys[newkey[i]];
  }
  return newObj;
}
//数组转字符串完成加密
function toQueryPair(key, value) {
  if (typeof value == 'undefined') {
    return `&${key}=`;
  }
  return `&${key}=${value}`;
}

function encryption(arys) {
  var param = reverse(arys);
  var extra_str = "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
  if (Object.prototype.toString.call(param) !== '[object Object]') {
    return '';
  }
  let queryParam = '';
  for (let key in param) {
    if (param.hasOwnProperty(key)) {
      let value = param[key];
      // if(value){ 
      queryParam += toQueryPair(key, value);
      // }
    }
  }
  return queryParam.slice(1) + extra_str;
}

function encryption2(arys) {
  var extra_str = "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
  var jsonstr = JSON.stringify(reverse(arys));
  var str1 = jsonstr.replace(new RegExp(":", "g"), "=");
  var str2 = str1.replace(new RegExp(",", "g"), "&");
  var str3 = str2.substring(1, str2.length - 1) + extra_str;
  var _token = str3.replace(/\"/g, "");
  return _token;
}

//获取wx.getStorageSync并判断是否有某个值
function isgetStorageSync(stor_name, user_id) {
  if (wx.getStorageSync(stor_name)) {
    var stor_name = JSON.parse(wx.getStorageSync(stor_name));
    var result = stor_name.some(function (item) {
      if (item.user_id === user_id) {
        return true
      }
    })
    return result
  }
}
//上麦才能发表情包
function isgogogogo(arr, id) {
  var result = arr.some(function (item) {
    if (item.user_id === id) {
      return true
    }
  })
  return result
}
//有一个false全部为false
function isupshow(arr) {
  var result = arr.some(function (item) {
    if (item.upshow === false) {
      return true
    }
  })
  return result
}
//数组中是否有某个值
function isuser_id(array, user_id) {
  let result = array.find(item => item.user_id == user_id.result.userId)
  return result.position
}
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatTimeTwo(number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  var date = new Date(number * 1000); //时间戳为10位 这边如果不乘以1000的话会全部出现1970的时间
  // var date = new Date(number );//时间戳为13位
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
/**
 * 选择上传照片
 * page_that:调用方法的页面，
 * cb_key:返回参数数组的名称
 * count:上传张数
 * 返回值：数组
 */
// function selecImg(page_that, cb_key, count) {
//   console.log("选择图片");
//   wx.chooseImage({
//     count: count,
//     sizeType: ['compressed'],
//     sourceType: ['album', 'camera'],
//     success: function(res) {
//       console.log(res)
//       var pathArray = [];
//       var PicNums = res.tempFiles.length;
//       for (var inta = 0; inta < PicNums; inta++) {
//         var size = res.tempFiles[inta].size;
//         var path = res.tempFiles[inta].path;
//         var formatImage = path.split(".")[(path.split(".")).length - 1];
//         console.log("图片格式" + formatImage)
//         if (formatImage != "png" && formatImage != "jpg" && formatImage != "jpeg") {
//           return wx.showToast({
//             title: '只能上传.png、.jpg、.jpep 格式',
//             icon: 'none',
//             image: '',
//             duration: 2000,
//             mask: true,
//           })
//         }
//         if (config.image_size < size) {
//           return wx.showToast({
//             title: '图片大小限制:' + (config.image_size / 1024 / 1024) + "MB",  ///config.image_size 配置文件中设置
//             icon: 'none',
//             image: '',
//             duration: 1500,
//             mask: true,
//           })
//         }
//         pathArray.push(path);
//         if (inta == PicNums-1) {
//           var cb = {};
//           cb[cb_key] = pathArray;
//           page_that.setData(cb);
//         }
//       }
//     }
//   })
// }

module.exports = {
  axios,
  encryption,
  encryption2,
  isgetStorageSync,
  isuser_id,
  isgogogogo,
  isupshow,
  formatTimeTwo,
  formatTime,
  testInterface,
  Decrypt, //解密
  Encrypt, //加密
  // selecImg,//上传图片
}
